package yh.platform.core.util;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author yifei.han
 * @version 1.0
 * @className JiujiuctFileUtil
 * @description
 * @date 2023/3/7
 */
@Slf4j
public class JiujiuctFileUtil {

    public static File downloadImg(String fileUrl, String downloadPath) {
        CloseableHttpClient httpclient;
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(12000).
                setConnectionRequestTimeout(12000).setSocketTimeout(12000).build();
        httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .setDefaultRequestConfig(requestConfig).build();
        File file = null;
        try {
            HttpGet get = new HttpGet(fileUrl);
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            InputStream in = entity.getContent();
            String extName = fileUrl.substring(fileUrl.lastIndexOf("."));
            String imagePath = downloadPath;
            file = new File(imagePath, UUID.randomUUID() + extName);
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                int l = -1;
                byte[] tmp = new byte[1024];
                while ((l = in.read(tmp)) != -1) {
                    fout.write(tmp, 0, l);
                }
                fout.flush();
            } finally {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 关闭低层流。
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e1) {
            log.info("下载图片出错" + fileUrl);
        }
        try {
            httpclient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

}
